package com.lz.springcloud.login.controller;

import java.util.Random;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.lz.springcloud.login.service.LoginService;
import com.lz.springcloud.tools.common.ToolsServiceFegin;

@RestController
@RequestMapping("login")
public class LoginController {
	@Autowired
	LoginService loginService;
	@Autowired
	ToolsServiceFegin toolsServiceFegin;

	@GetMapping("in")
	public boolean loginIn(String name, String password, String code, HttpServletResponse res) {
		//假定都可以登录
		String token="sso-token="+name+password;
		toolsServiceFegin.add(token, name+password+code);
		Cookie cookie=new Cookie("auth-token",token);
		res.addCookie(cookie);
		return true;
	}

	@GetMapping("code")
	public String code(HttpServletRequest req) {
		String code = "";
		while (code.length() < 4) {
			code += (int) Math.floor(new Random().nextInt(10));
		}
		return code + "" + req.getSession().getId();
	}

	@GetMapping("out")
	public boolean loginOut(HttpServletRequest req) {
		String key=null;
		Cookie[] cookies=req.getCookies();
		if(cookies!=null) {
		for(Cookie c:cookies) {
			if(c.getName().equals("auth-token")) {
				key=c.getValue();
			}
		}
		}
		if(key==null) {
			return true;
		}
		return toolsServiceFegin.del(key);
	}
	@GetMapping("getUser")
	public String getUser(HttpServletRequest req) {
		String key=null;
		Cookie[] cookies=req.getCookies();
		if(cookies!=null) {
		for(Cookie c:cookies) {
			if(c.getName().equals("auth-token")) {
				key=c.getValue();
			}
		}
		}
		if(key==null) {
			return "未登录";
		}
		String res = toolsServiceFegin.get(key);
		if(res==null) {
			return "未登录";
		}
		return res;
	}
}
